<template>
    <view class="housekeep-service" @click="categoryFilterShow = sortFilterShow = false">
        <header-vue title="家政服务" :back="true" backUrl="/pages/main?url=0" titPosition="left">
            <template v-slot:btnLt>
                <view class="h-btn-lt" @click="getOrderList">
                    <u-image class="icon-dd" :src="IMAGE_URL + '/static/housekeep/icon-dd.png'" width="28rpx" height="32rpx" mode="aspectFit"></u-image>  
                    <view>订单</view>
                </view>
            </template>
        </header-vue>
        <view class="service-content">
            	<view class="flex center search margin32">
                <i class="iconfont icon-search font40" @click.stop="handleSearch"></i>
                <input v-model="searchText" placeholder="搜索" class="input" confirm-type="search" @confirm="handleSearch"/>
            </view>
            
            <!-- 服务分类网格 -->
            <view class="service-categories">
                <view class="category-item" v-for="(item, index) in categories" :key="index" @click="selectCategory(item)">
                    <view class="category-icon">
                        <u-image :src="IMAGE_URL + '/static/housekeep/'+item.icon+'.png'" width="106rpx" height="106rpx" mode="aspectFit"></u-image>
                        <span class="iconfont" :class="item.icon"></span>
                    </view>
                    <text class="category-name">{{ item.title }}</text>
                </view>
            </view>
            
            <!-- 筛选按钮 -->
            <view class="filter-section">
                <view class="filter-btn" :class="{'active': categoryFilterShow}" @click.stop="showCategoryFilter">
                    <text>{{ selectedCategory }}</text>
                    <u-icon class="icon-arrow-down" name="arrow-down" size="12"></u-icon>
                </view>
                <view class="filter-btn" :class="{'active': sortFilterShow}" @click.stop="showSortFilter">
                    <text>{{ selectedSort }}</text>
                    <u-icon class="icon-arrow-down" name="arrow-down" size="12"></u-icon>
                </view>
                 <!-- 选择框展示区域 -->
                <view class="filter-pop-section" v-show="categoryFilterShow || sortFilterShow">
                    <!-- 分类筛选选择框 -->
                    <view class="filter-pop-container" v-show="categoryFilterShow">
                        <filter-pop 
                            :list="categoryFilterList" 
                            :selectedValue="selectedCategory"
                            @radioChange="onCategoryFilterChange"
                            :activeColor="'#007AFF'"
                            :placement="'column'"
                        />
                    </view>
                    
                    <!-- 排序筛选选择框 -->
                    <view class="filter-pop-container" v-show="sortFilterShow">
                        <filter-pop 
                            :list="sortFilterList" 
                            @radioChange="onSortFilterChange"
                            :activeColor="'#007AFF'"
                            :placement="'column'"
                        />
                    </view>
                </view>
            </view>
            
            <!-- 服务列表 -->
            <view class="service-list">
                <view class="service-item" v-for="(item, index) in serviceList" :key="index" @click="goToServiceDetail(item)">
                    <view class="service-image">
                        <u-image :src="IMAGE_URL+item.image" mode="aspectFill" width="200rpx" height="176rpx" adius="16rpx"></u-image>
                    </view>
                    <view class="service-info">
                        <text class="service-title">{{ item.name }}</text>
                        <view class="service-price-wrap">
                            <view class="service-price">
                                <view class="price">
                                    <text class="font24 color-red">¥</text>
                                    <text class="font36 color-red">{{ priceFormat(item.base_price)[0] }}.</text>
                                    <text class="font24 color-red">{{ priceFormat(item.base_price)[1] }}</text>
                                </view>
                                <text class="duration">/ {{ item.price_type + item.price_unit }}</text>
                            </view>
                            <text class="sales-count">已售{{ item.sale_count }}</text>
                        </view>
                    </view>
                </view>
            </view>
            
            <!-- 没有更多数据提示 -->
            <view v-if="!loading && !hasMore" class="no-more-tip">
                <text>没有更多数据了</text>
            </view>
        </view>
    </view>
</template>

<script>
import headerVue from '@/components/header.vue'
import filterPop from '@/components/filter-pop/index.vue' // 引入 filter-pop 组件
import { getHousekeepServiceList, getHousekeepCategoryList } from '@/api/index.js'
import appConfig from '@/config/app.js'
export default {
    data() {
        return {
            // 统一分类数据（用于网格与筛选）
            categories: [],
            categoriesIcon: {
                '保洁清洗': 'icon1',
                '软装清洗': 'icon2',
                '电器清洗': 'icon3',
                '母婴服务': 'icon4',
                '家庭服务': 'icon5',
                '电器维修': 'icon6',
                '家具维修': 'icon7',
                '房屋维修': 'icon8',
                '家庭安装': 'icon9',
                '衣物洗护': 'icon10'
            },
            serviceList: [],
            categoryFilterShow: false,
            sortFilterShow: false,
            // 筛选列表由 categories 动态生成
            sortFilterList: [ // 排序筛选列表
                { name: '默认排序', active: true, id: 1 },
                { name: '好评优先', active: false, id: 2 },
            ],
            selectedCategory: '全部分类', // 当前选中的分类
            selectedSort: '默认排序', // 当前选中的排序方式
            sort: 1, // 与 sortFilterList 对应的排序参数
            // 查询参数与分页
            page: 1,
            limit: 10,
            loading: false,
            hasMore: true,
            categoryId: '', // 选中的分类ID（"全部分类" 为空）
            searchText: '', // 搜索框内容，用作接口 name
            IMAGE_URL: appConfig.IMAGE_URL,
        }
    },
    components: {
        headerVue,
        filterPop // 注册 filter-pop 组件
    },
    computed: {
        categoryFilterList() {
            const list = [{ name: '全部分类', active: this.selectedCategory === '全部分类' }]
            return list.concat(this.categories.map(c => ({ name: c.title, active: this.selectedCategory === c.name })))
        }
    },
    mounted() {
        this.resetAndFetch()    
        this.getHousekeepCategoryListEvent()
    },
    onReachBottom() {
        // 触底加载更多
        this.getHousekeepServiceListEvent()
    },
    methods: {
        selectCategory(category) {
            // 顶部网格选择：设置分类并重置列表
            this.categoryId = category?.id || ''
            this.selectedCategory = category?.title || '全部分类'
            this.resetAndFetch()
        },
        showCategoryFilter() {
            this.categoryFilterShow = !this.categoryFilterShow;
            this.sortFilterShow = false
        },
        showSortFilter() {
            this.sortFilterShow = !this.sortFilterShow;
            this.categoryFilterShow = false
        },
        goToServiceDetail(service) {
            console.log('跳转到服务详情:', service.title);
            // 跳转到服务详情页面
            uni.navigateTo({
                url: '/views/housekeep/service-details?id=' + service.id
            });
        },
        onCategoryFilterChange(e) {
            this.selectedCategory = e
            if (e === '全部分类') {
                this.categoryId = ''
            } else {
                const cat = this.categories.find(c => c.title === e)
                this.categoryId = cat ? cat.id : ''
            }
            this.categoryFilterShow = false; // 关闭选择框
            this.resetAndFetch()
        },
        onSortFilterChange(e) {
            // 重置所有选项的 active 状态
            this.sortFilterList.forEach(item => {
                item.active = false;
            });
            // 设置选中项为 active
            const selectedItem = this.sortFilterList.find(item => item.name === e);
            if (selectedItem) {
                selectedItem.active = true;
                this.selectedSort = selectedItem.name;
                this.sort = selectedItem.id || 1
            }
            this.sortFilterShow = false; // 关闭选择框
            this.resetAndFetch()
        },
        handleSearch() {
            // 使用输入框值作为 name 参数
            this.resetAndFetch()
        },
        // 判断价格是否小数点，有切割组合，没有在后面添加00
        priceFormat(price) {
            if (price.indexOf('.') > -1) {
                return [price.split('.')[0], (price.split('.')[1] || '00')];
            } else {
                return [price, '00']
            }
        },
        // 重置分页并请求
        resetAndFetch() {
            this.page = 1
            this.hasMore = true
            this.serviceList = []
            this.getHousekeepServiceListEvent()
        },
        // 列表数据
        getHousekeepServiceListEvent() {
            if (this.loading || !this.hasMore) return
            this.loading = true
            getHousekeepServiceList({
                category_id: this.categoryId,
                name: this.searchText,
                sort: this.sort,
                page: this.page,
                limit: this.limit
            }).then((res) => {
                if (res && res.errno === 0) {
                    const list = (res.data && res.data.list) || []
                    if (this.page === 1) {
                        this.serviceList = list
                    } else {
                        this.serviceList = this.serviceList.concat(list)
                    }
                    // 是否还有更多
                    if (!list.length || list.length < this.limit) {
                        this.hasMore = false
                    } else {
                        this.page += 1
                    }
                }
            }).finally(() => {
                this.loading = false
            })
        },
        // 获取服务分类列表
        getHousekeepCategoryListEvent() {
            getHousekeepCategoryList().then((res) => {
                if (res.errno === 0) {
                    this.categories = res.data
                    this.categories.forEach(item => {
                        item.icon = this.categoriesIcon[item.title]
                    })
                }
            })
        },
        // 获取订单列表
        getOrderList(){
            uni.navigateTo({
                url: '/views/mine/myorder?tab=0'
            });
        }
    }
}
</script>
<style lang="scss" scoped>
.housekeep-service {
    padding-bottom: 20rpx;
    .service-content {
        padding: 28rpx 0 0 0;
        background: linear-gradient( 180deg, #F3F6FC 0%, #FFFFFF 100%);
    }
    .service-text {
        margin-bottom: 20rpx;
        font-size: 28rpx;
        color: #333;
    }
    .service-agreement {
        font-size: 24rpx;
        color: #666;
        line-height: 1.6;
    }
    .h-btn-lt {
        font-family: Alibaba PuHuiTi, Alibaba PuHuiTi;
        font-weight: 400;
        font-size: 28rpx;
        color: #0785CF;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .icon-dd {
            margin: 5rpx 5rpx 0 0 ;
        }
    }
    
    .margin32 {
		margin: 0 32rpx;
	}
	
	.search {
		height: 72rpx;
		background: $uni-bg-color;
		border-radius: 60rpx;
		padding: 0 28rpx;
		
		.iconfont {
			color: $uni-text-color-grey;
			margin-right: 20rpx;
		}
		
		.input {
			width: 100%;
			height: 100%;
		}
	}
	
	// 服务分类网格
	.service-categories {
		display: grid;
		grid-template-columns: repeat(5, 1fr);
		gap: 20rpx;
		padding: 40rpx 32rpx;
		
		.category-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			cursor: pointer;
			
			.category-icon {
				width: 100%;
				height: 90rpx;
				border-radius: 16rpx;
				display: flex;
				justify-content: center;
				margin-bottom: 12rpx;
				
				.iconfont {
					font-size: 36rpx;
					color: #FFFFFF;
				}
			}
			
			.category-name {
				font-size: 24rpx;
				color: #333333;
				text-align: center;
				line-height: 1.2;
			}
		}
	}
	
	// 筛选按钮
	.filter-section {
        position: relative;
		display: flex;
		padding: 0 32rpx 20rpx;
        
		.filter-btn {
            padding: 0 15rpx;
            height: 52rpx;
            background: #FFFFFF;
            box-shadow: 0rpx 0rpx 12rpx 0rpx rgba(0,0,0,0.08);
            border-radius: 8rpx 8rpx 8rpx 8rpx;
            color: #333333;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
            margin-right: 20rpx;

            &.active {
                .icon-arrow-down {
                    transform: rotate(180deg);
                }
            }
			
			text {
				font-size: 24rpx;
				color: #333333;
			}
			
			.icon-arrow-down {
                margin-left: 6rpx;
				font-size: 20rpx;
				color: #999999;
                transition: transform 0.3s ease;
			}
		}
	}

    // 选择框展示区域
    .filter-pop-section {
        position: absolute;
        z-index: 3;
        top: 52rpx;
        width: 100%;
        left: 50%;
        transform: translateX(-50%);
        background: #FFFFFF;
        box-shadow: 0rpx 0rpx 12rpx 0rpx rgba(0,0,0,0.08);
    }

    .filter-pop-container {
        padding:20rpx 0;
        border-bottom: 1rpx solid #EEEEEE;

        &:last-child {
            border-bottom: none;
        }

        .filter-pop-title {
            font-size: 28rpx;
            color: #333333;
            margin-bottom: 16rpx;
            padding-left: 10rpx;
        }
    }
	
	// 服务列表
	.service-list {
		padding: 0 32rpx;
		
		.service-item {
			display: flex;
			padding: 20rpx;
            height: 176rpx;
			background: #FFFFFF;
			border-radius: 16rpx;
			margin-bottom: 20rpx;
			cursor: pointer;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
			
			.service-image {
                width: 200rpx;
                height: 176rpx;
                border-radius: 16rpx 16rpx 16rpx 16rpx;
				overflow: hidden;
			}
			
			.service-info {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
                margin-left: 28rpx;
				
				.service-title {
					font-family: Alibaba PuHuiTi, Alibaba PuHuiTi;
                    font-weight: 500;
                    font-size: 28rpx;
                    color: #333333;
					line-height: 1.4;
					margin-bottom: 12rpx;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					overflow: hidden;
				}

                .service-price-wrap {
                    display: flex;
                    justify-content: space-between;
                    align-items: flex-end;
                }
				
				.service-price {
                    display: flex;
                    align-items: flex-end;
					
					.price {
						font-size: 32rpx;
						color: #FF6B6B;
						font-weight: 600;
					}
					
					.duration {
						font-size: 24rpx;
						color: #999999;
					}
				}
				
				.sales-count {
					font-size: 24rpx;
					color: #999999;
				}
			}
		}
	}

    // 加载更多
    .loading-tip {
        text-align: center;
        margin: 20rpx 0;
    }

    .no-more-tip {
        text-align: center;
        margin: 20rpx 0;
        font-size: 24rpx;
        color: #999999;
    }
}
</style>
